<?php
require('Zend/Loader/Autoloader.php');
/**
 * PicasaUploader Class
 * @author thaodx@gmail.com
 * @desc Upload photo from local to picasa server
 *       Auto create album to upload
 */
class PicasaUploader extends Zend_Loader_Autoloader{
	var $gp = null;
	const ALBUM_PREFIX = 'cgt_';
	const LIMIT_PHOTO = 499; // limit number of photo in a album
	public function __construct($user, $pass){
		try{
			parent::getInstance();
			$serviceName = Zend_Gdata_Photos::AUTH_SERVICE_NAME;
			$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $serviceName);
			// update the second argument to be CompanyName-ProductName-Version
			$this->gp = new Zend_Gdata_Photos($client, "Google-DevelopersGuide-1.0");
		}
		catch (Zend_Gdata_App_HttpException $e) {
		    echo "Error: " . $e->getMessage() . "<br />\n";
		    if ($e->getResponse() != null) {
		        echo "Body: <br />\n" . $e->getResponse()->getBody() . 
		             "<br />\n"; 
		    }
		}
		catch (Zend_Gdata_App_Exception $e) {
		    echo "Error: " . $e->getMessage() . "<br />\n"; 
		}
	}
	public function getAlbums(){
	    $albums = array();
	    $query = new Zend_Gdata_Photos_UserQuery();
	    $query->setUser("default");
	    $query->setType("entry");

	    $results = $this->gp->getUserFeed(null, $query);
	    while($results != null) {
	        foreach($results as $entry) {
	            $album_id = $entry->gphotoId->text;//$entry->getId();//$entry->getGphotoId()->getText();
	            $album_name = $entry->title->text;
	            $album_pdate = $entry->published->text;
				$numphoto = $entry->gphotoNumPhotos->text;

	            $albums[] = array(
	                'id' => $album_id,
	                'name' => $album_name,
	                'pdate' => $album_pdate,
	                'numphoto' => $numphoto
	            );
	        }

	        try {
	            $results = $results->getNextFeed();
	        }
	        catch(Exception $e) {$results = null;}
	    }

	    return $albums;
	}

	public function getPhotos($album_id) {
	    $photos = array();
	    $query = new Zend_Gdata_Photos_AlbumQuery();
	    $query->setAlbumId($album_id);
	    // http://code.google.com/intl/ru/apis/picasaweb/docs/2.0/reference.html
	    $query->setThumbsize(144);
	    $query->setImgMax(800);
	    $results = $this->gp->getAlbumFeed($query);
	    while($results != null) {
	        foreach($results as $entry) {
	            foreach($results as $photo) {
	                //thumbnail(s): $photo->mediaGroup->thumbnail[0]->url
	                //fullsize: $photo->mediaGroup->content[0]->url
	                $photos[] = array(
	                    'thumbnail' => $photo->mediaGroup->thumbnail[0]->url,
	                    'fullsize' => $photo->mediaGroup->content[0]->url
	                );
	            }
	        }
	        try {
	            $results = $results->getNextFeed();
	        }
	        catch(Exception $e) {$results = null;}
	    }

	    return $photos;
	}
	public function createAlbum($name){
	  $entry = new Zend_Gdata_Photos_AlbumEntry();
	  $entry->setTitle($this->gp->newTitle($name));

	  return $this->gp->insertAlbumEntry($entry);
	}
	public function uploadPhoto($file, $name = ''){
		if($name == '') $name = self::ALBUM_PREFIX . date('dmyHis') . rand(1, 99);
	  	$albumId = 0;
	  	$numberPhoto = 0;
	  	try{
		  $ext = strtolower(end(explode('.', $file)));
		  switch($ext){
		  	case "jpg":
		  	case "jpeg":
		  		$mime = "image/jpeg";
		  		break;
		  	case "gif":
		  		$mime = 'image/gif';
		  		break;
		  	case "png":
		  		$mime = 'image/png';
		  		break;
		  	case "bmp":
		  		$mime = 'image/bmp';
		  		break;
		  	default:
		  		$mime = 'image/jpeg';
		  		break;	  		
		  }
		  // get latest album
		  $arrAlbum = self::getAlbums();
		  foreach($arrAlbum as $album) {
		  	if(preg_match('/^' . self::ALBUM_PREFIX . '(.+)$/is', $album['name'])){
		  		$albumId = $album['id'];
		  		$numberPhoto = (int)$album['numphoto'];
		  		break;
		  	}
		  }
		  // create new album if limit reached at latest album
		  if($numberPhoto >= self::LIMIT_PHOTO || $albumId == 0){
		  	$newAlbum = self::createAlbum(self::ALBUM_PREFIX . date('dmY'));
		  	$albumId = $newAlbum->gphotoId->text;
		  }
		  $fd = $this->gp->newMediaFileSource($file);
		  $fd->setContentType($mime);
		  // Create a PhotoEntry
		  $photoEntry = $this->gp->newPhotoEntry();
		  $photoEntry->setMediaSource($fd);
		  $photoEntry->setTitle($this->gp->newTitle($name));
		  // We use the AlbumQuery class to generate the URL for the album
		  $albumQuery = $this->gp->newAlbumQuery();
		  $albumQuery->setAlbumId($albumId);
		  // We insert the photo, and the server returns the entry representing
		  // that photo after it is uploaded
		  $return = $this->gp->insertPhotoEntry($photoEntry, $albumQuery->getQueryUrl());
		  $return = $return->content->src;
		}
	  catch(Exception $e) {$return = null;}
	  return $return;
	}
}